<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto" style="display: flex;">
        <!-- 使用el-row和el-col实现一行两列布局 -->
        <el-row :gutter="10" style="display:flex;flex-wrap: wrap">
          <el-col :span="12">
            <el-form-item label="产线" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptOptions" :flat="true" :normalizer="normalizer"
                          placeholder="选择产线" style="width: 100%" :default-expand-all="true" @select="handleDeptSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="段别" prop="segmentId">
              <el-select v-model="formData.segmentId" clearable placeholder="请选择段别" filterable style="width: 100%" @change="handleSegmentChange">
                <el-option v-for="item in segmentList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级损失原因" prop="lossOneId">
              <el-select v-model="formData.lossOneId" filterable clearable placeholder="请选择一级损失原因" style="width: 100%" @change="handleLossOneChange">
                <el-option v-for="item in lossOneList" :key="item.id" :label="item.lossName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级损失原因" prop="lossTwoId">
              <el-select v-model="formData.lossTwoId" clearable filterable placeholder="请选择二级损失原因" style="width: 100%" :disabled="!formData.lossOneId" @change="handleLossTwoChange">
                <el-option v-for="item in lossTwoList" :key="item.id" :label="item.lossName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="开始时间" prop="startDateTime">
    <el-date-picker clearable v-model="formData.startDateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间" style="width: 100%" @change="calculateLossMins"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="结束时间" prop="endDateTime">
    <el-date-picker clearable v-model="formData.endDateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间" style="width: 100%" @change="calculateLossMins"/>
  </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="损失分钟" prop="lossMins">
              <el-input v-model="formData.lossMins" placeholder="请输入损失分钟" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="损失占比(%)" prop="ratio">
              <el-input v-model="formData.ratio" placeholder="请输入损失占比(%)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任产线" prop="liabilityDeptId">
              <treeselect v-model="formData.liabilityDeptId" :options="deptOptions" :flat="true" :normalizer="normalizer"
                          placeholder="选择责任产线" style="width: 100%" :default-expand-all="true" @select="handleLiabilityDeptSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理结果" prop="handlerResult">
              <el-select v-model="formData.handlerResult" placeholder="请选择处理结果" style="width: 100%">
                <el-option label="OPEN" value="OPEN"/>
                <el-option label="CLOSE" value="CLOSE"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理日期" prop="handlerDate">
              <el-date-picker clearable v-model="formData.handlerDate" type="date" value-format="yyyy-MM-dd" placeholder="选择处理日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as LossAnalysisApi from '@/api/lamp/lossanalysis';
import * as LossReasonApi from '@/api/lamp/lossreason';
import * as SegmentApi from '@/api/lamp/segment';
import { listDept } from '@/api/system/dept';
import { listUser } from '@/api/system/user';
import { listPost } from '@/api/system/post';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "LossAnalysisForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        deptId: undefined,
        deptName: undefined,
        postId: undefined,
        postName: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
        segmentId: undefined,
        segmentName: undefined,
        startDateTime: undefined,
        endDateTime: undefined,
        lossOneId: undefined,
        lossOneName: undefined,
        lossTwoId: undefined,
        lossTwoName: undefined,
        lossMins: undefined,
        ratio: undefined,
        liabilityDeptId: undefined,
        liabilityDeptName: undefined,
        remark: undefined,
        handlerResult: undefined,
        handlerDate: undefined,
      },
      // 表单校验
      formRules: {},
      // 产线树选项
      deptOptions: [],
      // 用户列表
      userList: [],
      // 工位列表
      postList: [],
      // 段别列表
      segmentList: [],
      // 一级损失原因列表
      lossOneList: [],
      // 二级损失原因列表
      lossTwoList: []
    };
  },
  created() {
    this.getOptions();
  },
  methods: {
      calculateLossMins() {
    if (this.formData.startDateTime && this.formData.endDateTime) {
      try {
        // 将字符串格式的日期时间转换为Date对象
        const startTime = new Date(this.formData.startDateTime);
        const endTime = new Date(this.formData.endDateTime);

        // 检查日期转换是否成功
        if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
          this.$message.error('日期格式不正确，请重新选择');
          return;
        }

        // 确保开始时间不晚于结束时间
        if (startTime > endTime) {
          this.$message.error('开始时间不能晚于结束时间');
          return;
        }

        // 计算分钟差（毫秒转分钟）
        const minutes = Math.floor((endTime.getTime() - startTime.getTime()) / (1000 * 60));
        this.formData.lossMins = minutes;
      } catch (error) {
        this.$message.error('计算损失分钟失败，请检查日期格式');
      }
    }
  },
    // 处理工位选择变化
    handlePostChange(postId) {
      const post = this.postList.find(item => item.id === postId);
      if (post) {
        this.formData.postName = post.name;
      }
    },

    // 处理操作员选择变化
    changeUser(userId) {
      const user = this.userList.find(item => item.id === userId);
      if (user) {
        this.formData.operatorName = user.username;
        this.formData.operatorIdCard = user.idCard;
      }
    },

    // 处理段别选择变化
    handleSegmentChange(segmentId) {
      const segment = this.segmentList.find(item => item.id === segmentId);
      if (segment) {
        this.formData.segmentName = segment.name;
      }
    },

    // 处理一级损失原因选择变化
    async handleLossOneChange(lossOneId) {
      const lossOne = this.lossOneList.find(item => item.id === lossOneId);
      if (lossOne) {
        this.formData.lossOneName = lossOne.lossName;
        // 清空二级损失原因
        this.formData.lossTwoId = undefined;
        this.formData.lossTwoName = undefined;
        // 查询二级损失原因
        try {
          const res = await LossReasonApi.getLossReasonPage({ parentId: lossOneId, pageSize: 100 });
          this.lossTwoList = res.data.list;
        } catch (error) {
          this.$message.error('获取二级损失原因失败');
          this.lossTwoList = [];
        }
      } else {
        this.formData.lossOneName = undefined;
        this.formData.lossTwoId = undefined;
        this.formData.lossTwoName = undefined;
        this.lossTwoList = [];
      }
    },

    // 处理二级损失原因选择变化
    handleLossTwoChange(lossTwoId) {
      const lossTwo = this.lossTwoList.find(item => item.id === lossTwoId);
      console.log(lossTwo)
      if (lossTwo) {
        this.formData.lossTwoName = lossTwo.lossName;
      } else {
        this.formData.lossTwoName = undefined;
      }
    },

    // 处理产线选择
    handleDeptSelect(deptId) {
      if (deptId && deptId.name) {
        this.formData.deptName = deptId.name;
      }
    },

    // 处理责任产线选择
    handleLiabilityDeptSelect(deptId) {
      if (deptId && deptId.name) {
        this.formData.liabilityDeptName = deptId.name;
      }
    },


    // 获取产线树数据
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id';
      parentId = parentId || 'parentId';
      children = children || 'children';
      rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0;
      // 对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      // 循环所有项
      const treeData = cloneData.filter(father => {
        // 返回每一项的子级数组
        const branchArr = cloneData.filter(child => {
          // 匹配子级
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? father[children] = branchArr : delete father[children];
        // 返回第一层
        return father[parentId] === rootId;
      });
      return treeData !== '' ? treeData : data;
    },

    /** 获取下拉框选项 */
    async getOptions() {
      try {
        // 获取产线列表
        const deptRes = await listDept({ pageNo: 1, pageSize: 100 });
        this.deptOptions = this.addLevelToNodes(this.handleTree(deptRes.data, "id"), 1);

        // 获取用户列表
        const userRes = await listUser({ pageSize: 100, pageNo: 1 });
        this.userList = userRes.data.list;

        // 获取工位列表
        const postRes = await listPost({ pageSize: 100, pageNo: 1 });
        this.postList = postRes.data.list;

        // 获取段别列表
        const segmentRes = await SegmentApi.getSegmentPage({ pageSize: 100, pageNo: 1 });
        this.segmentList = segmentRes.data.list;

        // 获取一级损失原因列表 (parentId=0)
        const lossOneRes = await LossReasonApi.getLossReasonPage({ parentId: 0, pageSize: 100 });
        this.lossOneList = lossOneRes.data.list;
      } catch (error) {
        this.$message.error('获取选项数据失败');
      }
    },

        // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },


    // 产线树数据格式化
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children
      };

      // 如果不是type==3的产线，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },




    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await LossAnalysisApi.getLossAnalysis(id);
          this.formData = res.data;
          this.dialogTitle = "修改损失工时分析";
          // 如果有一级损失原因，需要加载二级损失原因
          if (this.formData.lossOneId) {
            const lossTwoRes = await LossReasonApi.getLossReasonPage({ parentId: this.formData.lossOneId, pageSize: 100 });
            this.lossTwoList = lossTwoRes.data.list;
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增损失工时分析";
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await LossAnalysisApi.updateLossAnalysis(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await LossAnalysisApi.createLossAnalysis(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        deptId: undefined,
        deptName: undefined,
        postId: undefined,
        postName: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
        segmentId: undefined,
        segmentName: undefined,
        startDateTime: undefined,
        endDateTime: undefined,
        lossOneId: undefined,
        lossOneName: undefined,
        lossTwoId: undefined,
        lossTwoName: undefined,
        lossMins: undefined,
        ratio: undefined,
        liabilityDeptId: undefined,
        liabilityDeptName: undefined,
        remark: undefined,
        handlerResult: undefined,
        handlerDate: undefined,
      };
      this.lossTwoList = [];
      this.resetForm("formRef");
    }
  }
};
</script>

<style scoped>
/* 确保所有表单组件宽度一致 */
:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker),
:deep(.vue-treeselect) {
  width: 100% !important;
  box-sizing: border-box;
}
</style>
